package com.fone.player.play.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.fone.player.AndroidPlayer;
import com.fone.player.ApplicationManage;
import com.fone.player.FonePlayer;
import com.fone.player.FonePlayer.OnCloseSuccessListener;
import com.fone.player.FonePlayer.OnCompletionListener;
import com.fone.player.FonePlayer.OnNewSubtitleListener;
import com.fone.player.FonePlayer.OnOpenDoneListener;
import com.fone.player.FonePlayer.OnOpenFailedListener;
import com.fone.player.FonePlayer.OnOpenPercentListener;
import com.fone.player.FonePlayer.OnOpenSuccessListener;
import com.fone.player.FonePlayer.OnPreparedListener;
import com.fone.player.FonePlayer.OnShowEngineTypeListener;
import com.fone.player.R;
import com.fone.player.TagFoneMediaDesc;
import com.fone.player.TagFoneMediaInfo;
import com.fone.player.activity.personal.PlayRecordFragment;
import com.fone.player.airone.AirOne;
import com.fone.player.airone.AirServerDevice;
import com.fone.player.airone.FAirPlay;
import com.fone.player.airone.FDLNAPlay;
import com.fone.player.client.Configure;
import com.fone.player.client.Reporter;
import com.fone.player.client.VgdetailRst;
import com.fone.player.client.VgdetailRst.From;
import com.fone.player.client.XyzplaRst;
import com.fone.player.entity.CacheVideo;
import com.fone.player.entity.PlayRecord;
import com.fone.player.play.ChangeVideoEvent;
import com.fone.player.play.IPlayerAdapter;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerStateMachine;
import com.fone.player.play.VideoMode;
import com.fone.player.play.VideoPlayerMessage;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;

import de.greenrobot.event.EventBus;
import dlna.CDLNAPlayer;

/**
 * 播放器适配器,控制播放
 * 
 * @author kongxiaojun
 * @since 2014-4-18
 * 
 */
public abstract class FonePlayerAdapter implements IPlayerAdapter {
	/**
	 * 省电加速开关 0.关 1.开
	 * */
	private static int hardware_plus = 0;
	/***
	 * 硬件解码开关0.关 1.开
	 */
	private static int system_decoder = 0;
	/**
	 * vip视频最大免费时长5分钟，当后台配置时长超过此时长时，后台配置无效
	 */
	private static final int MAX_VIP_FREE_TIME = 300000;
	/** log Tag */
	private static final String TAG = "FonePlayerAdapter";
	/** 视频播放类 */
	private FonePlayer player;
	/** 显示视频SurfaceView */
	private SurfaceView videoSurface;
	/** 视频模版 */
	private VideoMode mode;
	private PlayerStateMachine machine;
	private int lastPosition;
	/** 当前播放进度,单位毫秒 */
	private int currentPostion;
	/** 视频持续时间，单位毫秒 */
	private int videoDuration;
	/** 开一个线程池 */
	private ExecutorService threadPool;
	/** 线程池大小 */
	private int poolSize = 5;
	/** 是否正在播放 */
	private boolean isPlaying;
	/** 更新播放位置线程 */
	private AirOneStateThread aironeThread;
	/** 当前播放器播放数据 */
	private TagFoneMediaInfo currentMedia;
	/** 视频详情 */
	private VgdetailRst videoDetail;
	/** 视频来源 */
	private From currentFrom;
	/** 缓存来源 */
	private From cacheFrom;
	/** 播放视频地址列表 */
	private String[] urls;
	/** 当前播放地址索引 */
	private int playIndex;
	/** 播放数据 */
	private XyzplaRst plaRst;
	/** 视频宽 */
	private int mediaWidth;
	/** 视频高 */
	private int mediaHeight;
	/** 当前播放的xyzPlayUrl，或者本地视频文件的绝对地址 */
	private String xyzPlayUrl;
	/** 是否已经恢复了播放记录，每一个视频的第一次准备完成时进行恢复播放记录 */
	private boolean hasResumedPlayRecord = false;
	/** 资源服务器地址 */
	private String shost;
	/** 多片播放时播放的url索引 */
	protected int airIndex;
	/**
	 * 当前倍速索引 0-->0.8倍速,1-->正常速度,2-->1.5倍速,3-->1.8倍速,4-->2倍速
	 */
	private int currentRate = 1;
	/** 正在缓冲标志 */
	private boolean buffering = false;
	/** 是否是缓存视频 */
	private boolean isCacheVideo = false;
	/** 是否缓存完成 */
	private boolean cacheFinish = false;
	/** 缓存的视频 */
	private ArrayList<CacheVideo> cacheVideos;
	/** 是否加密视频 */
	private boolean encryption = false;
	/** 已经投放的设备 */
	private Map<String, AirServerDevice> deviceMap = new LinkedHashMap<String, AirServerDevice>();
	private Lock deviceMapLock = new ReentrantLock();
	private String videoName;
	/** airone正在转化中 */
	private boolean aironeTranslating = false;
	/** 是否vip影片 */
	private boolean vip;
	/** 影片免费时长(毫秒) */
	private int ft;
	/** 是否来自原网页视频 */
	private boolean fromWebView;
	public static boolean isCloseSuccess = true;
	private Handler mHandler;
	private boolean openDone = true;
	private boolean systemPlayerOpenFailed = false;
	private boolean playerRelease = false;
	private boolean playerStop = false;
	private boolean isSeeking;
	/**
	 * 0:hw 1:sys 2:sw
	 */
	private int engineType = -1;
	
	private int comeFrom;


	public FonePlayerAdapter(SurfaceView videoSurface) {
		super();
		this.videoSurface = videoSurface;
		machine = new PlayerStateMachine();
		mHandler = new Handler();
	}

	/** 打开url并播放 */
	private void open() {
		if (playerRelease) {
			return;
		}
		L.v(TAG, "wwb_message open");
		if (currentMedia == null || currentMedia.fragUrl == null || currentMedia.fragUrl.length == 0) {
			sendMessage2UI(FONE_PLAYER_MSG_VIDEO_OUT_LINE_TOAST);
			return;
		}
		try {
			L.v(TAG, "open url :" + currentMedia.fragUrl[0]);
			if (mode == VideoMode.LOCAL) {
				if (currentMedia.fragUrl[0].startsWith("/")) {
					File f = new File(currentMedia.fragUrl[0]);
					if (!f.exists()) {
						Toast.makeText(ApplicationManage.getAplicationManageInstance(), R.string.player_full_file_not_exist, Toast.LENGTH_SHORT).show();
						return;
					}
				}
			}
			playerStop = false;
			prepareOpen();
			player = new FonePlayer();
			player.open(currentMedia);
			player._setSurface(videoSurface.getHolder().getSurface());
			player.setOnPreparedListener(new PlayerOnPreparedListener()); // 当准备好的时候再播放
			player.setOnOpenSuccessListener(new FoneOnOpenSuccessListener());// 打开成功
			player.setOnOpenFailedListener(new FoneOnOpenFailedListener());// 打开失败
			player.setOnOpenPercentListener(new FoneOnOpenPercentListener());// 打开百分比
			player.setOnShowEngineTypeListener(new FoneOnShowEngineTypeLister());
			player.setOnNewSubtitleListener(new FoneOnNewSubtitleLister());
			player.setOnCloseSuccessListener(new FoneOnCloseSuccessListener());
			player.setOnOpenDoneListener(new FoneOnOpenDoneListener());
			sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PREPARING);
			machine.play();
			isPlaying = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void prepareOpen() {
		if (mode != VideoMode.LOCAL && !isCacheVideo) {
			setSystem_decoder(0);// 在线视频不支持硬解
			openDone = false;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					// 5秒超时后默认打开
					openDone = true;
				}
			}, 5000);
		}
	}

	/**
	 * 发送消息给UI
	 * 
	 * @param msg
	 */
	protected abstract void sendMessage2UI(Message msg);

	/** 发送消息给UI */
	private void sendMessage2UI(int what) {
		L.v(TAG, "sendMessage2UI Messgae what:" + what);
		Message msg = new Message();
		msg.what = what;
		sendMessage2UI(msg);
	}

	/**
	 * 准备完成监听
	 * 
	 * @author kongxiaojun
	 * @since 2014-4-16
	 * 
	 */
	private class PlayerOnPreparedListener implements OnPreparedListener {
		@Override
		public <T> void onPrepared(FonePlayer fp, T mediaInfoObj) {
			L.v(TAG, "player onPrepared!");
			buffering = false;
			isSeeking = false;
			videoSurface.setVisibility(View.VISIBLE);
			if (player != null && !playerStop) {
				L.v(TAG, "player onPrepared! videoSurface setVisibility VISIBLE");
				player.play();
				TagFoneMediaDesc mediaInfo = (TagFoneMediaDesc) mediaInfoObj;
				mediaWidth = mediaInfo.m_nWidth;
				mediaHeight = mediaInfo.m_nHeight;
				L.v(TAG, "onPrepared Width = " + mediaWidth + " Height = " + mediaHeight);
				videoDuration = mediaInfo.m_nMediaDuration;
				videoSurface.getHolder().setFixedSize(mediaWidth, mediaHeight);
				if (ApplicationManage.getGlobalContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					setSurfaceScale(frameScale);
				}
				L.v(TAG, "onPrep ared get videoDuration == " + videoDuration);
				player.setOnCompletionListener(new FonePlayerOnCompletionListener()); // 监听播放完成事件
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PREPARED);
			}
		}
	}

	/**
	 * 播放完成监听器
	 * 
	 * @author kongxiaojun
	 * @since 2014-4-16
	 * 
	 */
	private class FonePlayerOnCompletionListener implements OnCompletionListener {
		@Override
		public void onCompletion(FonePlayer fp, int type) {
			L.v(TAG, "player onCompletion!");
			if (type == 1) {// 整片播放完成
				// 直接seek到结束已经不会有openSuccess消息，导致不能返回，所以在这里把openDone置为true
				openDone = true;
				L.v(TAG, "wwb_message new player onCompletion stop start");
				if (engineType != 1) {
					player.stop(true); // 停止播放
				}
				L.v(TAG, "wwb_message player onCompletion stop end");
				if (currentPostion + 5000 < videoDuration && mode != VideoMode.LOCAL) {
					Toast.makeText(ApplicationManage.getAplicationManageInstance(), R.string.fullplayer_media_buffer_timeout, Toast.LENGTH_SHORT).show();
					if (engineType != 1) {
						player.release(); // 释放资源
						player = null; // 垃圾回收
					}
					savePlayRecord();
					updatePlayRecord2MediaInfo();
				} else {
					lastPosition = 0;
					currentPostion = videoDuration;
					if (engineType != 1) {
						player.release(); // 释放资源
						player = null; // 垃圾回收
					}
					savePlayRecord();
				}
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PLAY_COMPLETION);
				videoDuration = 0;
			} else {// 单片播放完成
				player.stop(false); // 停止播放
				if (player != null) {
					player._setSurface(videoSurface.getHolder().getSurface());
				}
			}
		}
	}

	private class FoneOnOpenSuccessListener implements OnOpenSuccessListener {
		@Override
		public void onOpenSuccess(FonePlayer fp) {
			L.v(TAG, "onOpenSuccess");
			
			Reporter.logPlayerOpen(xyzPlayUrl, (byte)comeFrom);
			if (mode == VideoMode.LOCAL) {
				Reporter.logPlayerFileSuffix(currentMedia.fragUrl[0]);
			}
			
			if (player != null) {
				openDone = true;
				L.v(TAG, "onOpenSuccess videoSurface setVisibility VISIBLE");
				videoSurface.setVisibility(View.VISIBLE);
				TagFoneMediaDesc mediaInfo = (TagFoneMediaDesc) player.getDesc();
				mediaWidth = mediaInfo.m_nWidth;
				mediaHeight = mediaInfo.m_nHeight;
				L.v(TAG, "onOpenSuccess Width = " + mediaWidth + " Height = " + mediaHeight);
				videoDuration = mediaInfo.m_nMediaDuration;
				videoSurface.getHolder().setFixedSize(mediaWidth, mediaHeight);
				if (ApplicationManage.getAplicationManageInstance().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					setSurfaceScale(frameScale);
				}
				if (encryption && lastPosition > 0) {
					player.seekTo(lastPosition);
					lastPosition = 0;
					return;
				}
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_OPEN_SUCCESS);
			}
		}
	}

	private class FoneOnOpenFailedListener implements OnOpenFailedListener {
		@Override
		// when sw player open failed, recv this.
		public void onOpenFailed(FonePlayer fp, int type) {
			openDone = true;
			L.v(TAG, "onOpenFailed");
			if (type == 1) {
				systemPlayerOpenFailed = true;
				// 硬解码打开失败，会自动切换到软解
				videoSurface.setVisibility(View.INVISIBLE);
				if (player != null) {
					L.v(TAG, "system player OpenFailed !");
					player.stop(false);
				}
				return;
			}
			if (player != null) {
				playerStop = true;
				savePlayRecord();
				hasResumedPlayRecord = false;
				isCloseSuccess = false;
				videoDuration = 0;
				L.v(TAG, "wwb_message player stopping");
				player.stop(true);
				player.release();
				player = null;
				machine.stop();
				lastPosition = currentPostion;
			}
			// }
			Message msg = new Message();
			msg.what = FONE_PLAYER_MSG_PLAYER_OPEN_FAILED;
			msg.arg1 = type;
			sendMessage2UI(msg);
		}
	}

	private class FoneOnOpenPercentListener implements OnOpenPercentListener {
		@Override
		public void onOpenPercent(FonePlayer fp, int percent) {
			if (mode != VideoMode.LOCAL) {
				// 显示打开的百分比
				if (!buffering) {
					buffering = true;
					sendMessage2UI(FONE_PLAYER_MSG_BUFFERING_START);
				}
				Message msg = new Message();
				msg.what = FONE_PLAYER_MSG_BUFFERING_PROGRESS;
				msg.arg1 = percent;
				sendMessage2UI(msg);
				L.v(TAG, "onOpenPercent " + percent);
			}
		}
	}

	private class FoneOnShowEngineTypeLister implements OnShowEngineTypeListener {
		public void onEngineType(FonePlayer fp, int engineType) {
			// msg.arg1 0:hw 1:sys 2:sw
			FonePlayerAdapter.this.engineType = engineType;
			L.v("liyang", "onEngineType ", engineType);
			if (player != null) {
				if (engineType == 1) {
					videoSurface.setVisibility(View.VISIBLE);
				} else {
					player._setSurface(videoSurface.getHolder().getSurface());
				}
			}
		}
	}

	private class FoneOnNewSubtitleLister implements OnNewSubtitleListener {

		@Override
		public void onNewSubtitle(String arg0) {
			// 新字幕
			Message msg = new Message();
			msg.what = FONE_PLAYER_MSG_PLAYER_UPDATE_SUBTITLE;
			msg.obj = arg0;
			sendMessage2UI(msg);
		}

	}

	private class FoneOnCloseSuccessListener implements OnCloseSuccessListener {
		@Override
		public void onCloseSuccess(FonePlayer fp) {
			L.v(TAG, "onCloseSuccess");
			L.v(TAG, "wwb_message new onCloseSuccess");
			Reporter.logPlayerClose();
			
			// 关闭完成后才可以进行open()
			isCloseSuccess = true;
			// 开始所有暂停的下载任务(先注释,后期需要再解开)
			// StorageModule.getInstance().startAllCache(
			// StorageModule.MSG_ACTION_OPERATE_PROGRAM_TYPE);
		}

	}

	private class FoneOnOpenDoneListener implements OnOpenDoneListener {
		@Override
		public void onOpenDone(FonePlayer arg0) {
			L.v(TAG, "wwb_message onOpenDone");
			L.v(TAG, "wwb_message set false in open done");
			isCloseSuccess = false;
		}
	}

	@Override
	public void pause() {
		L.v(TAG, "pause");

		Reporter.logPlayerPause();

		if (isAirOneMode()) {
			airOnePasue();
		} else if (player != null && player.isPlaying()) {
			player.pause();
			machine.pause();
			sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PLAYING_PAUSE);
		}
	}

	@Override
	public synchronized void stop() {
		L.v(TAG, "wwb_message stop start" + this.getClass());
		if (mHandler != null) {
			L.v(TAG, "wwb_message removeCallbacksAndMessages");
			mHandler.removeCallbacksAndMessages(null);
		}
		if (isAirOneMode()) {
			airOneStopAll();
		} else if (player != null) {
			playerStop = true;
			savePlayRecord();
			hasResumedPlayRecord = false;
			isCloseSuccess = false;
			videoDuration = 0;
			L.v(TAG, "wwb_message player stopping" + this.getClass());
			player.stop(true);
			if (player != null) {
				player.release();
				player = null;
			}
			machine.stop();
			lastPosition = currentPostion;
		}
		if (aironeThread != null) {
			aironeThread.setRelease(true);
			aironeThread.interrupt();
			aironeThread = null;
		}
		L.v(TAG, "wwb_message stop end" + this.getClass());
	}

	private void airOneStopAll() {

		Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, AirServerDevice> entry = it.next();
			AirServerDevice d = entry.getValue();
			d.checked = false;
			it.remove();
			airOneStop(d);
		}
	}

	@Override
	public synchronized void release() {
		if (aironeThread != null) {
			aironeThread.setRelease(true);
			aironeThread.interrupt();
			aironeThread = null;
		}
		if (threadPool != null) {
			threadPool.shutdown();
			threadPool = null;
		}
		openDone = true;
		currentRate = 1;
		// 关闭省电加速
		setHwPlusSupport(0);
		setSystem_decoder(0);
	}

	@Override
	public void seekTo(int progress) {
		L.v(TAG, "seekTo");
		L.v(TAG, "wwb_message start seekTo = " + progress);
		if (isAirOneMode()) {
			currentPostion = progress;
			if (ft != 0 && progress >= ft && vip && !UserInfoManager.isVip()) {// 非vip用户
				airOneStopAll();
				return;
			}
			airOneSeek(progress);
		} else if (mode != VideoMode.LIVE && player != null) {
			if (ft != 0 && progress >= ft && vip && !UserInfoManager.isVip()) {// 非vip用户
				// 非vip,暂停播放
				pause();
				sendMessage2UI(FONE_PLAYER_MSG_SHOW_VIP_PAGE);
				return;
			}
			isSeeking = true;
			if (FonePlayerAdapter.hardware_plus == 0 && currentMedia.fragUrl.length > 1 && getPlayIndexByPostion(currentPostion) != getPlayIndexByPostion(progress)) {
				L.v(TAG, "FonePlayerAdapter seekto frag videoSurface INVISIBLE");
				openDone = false;
				// 不在同一片
				videoSurface.setVisibility(View.INVISIBLE);
			}
			currentPostion = progress;
			player.seekTo(progress);
		}
	}

	@Override
	public boolean isPlaying() {
		L.v(TAG, "isPlaying");
		if (isAirOneMode()) {
			return isPlaying;
		}
		if (player != null) {
			isPlaying = player.isPlaying();
			L.v(TAG, "isPlaying == " + isPlaying);
			return isPlaying;
		}
		return false;
	}

	public boolean isPause() {
		L.v(TAG, "isPause");
		if (player != null) {
			isPlaying = player.isPlaying();
			return !isPlaying;
		}
		return false;
	}

	@Override
	public VideoMode getVideoMode() {
		return mode;
	}

	@Override
	public int getMediaDuration() {
		if (isAirOneMode()) {
			return videoDuration;
		}
		if (player != null) {
			return videoDuration;
		}
		return 0;
	}

	@Override
	public int getCurrentPosition() {
		if (isAirOneMode()) {
			if (ft != 0 && currentPostion >= ft && vip && !UserInfoManager.isVip()) {// 非vip用户
				// 非vip,停止投放,会自动调用本地 播放从而弹出vip计费页
				airOneStopAll();
			}
			if (currentPostion < 0) {
				currentPostion = 0;
			} else if (currentPostion > videoDuration) {
				currentPostion = videoDuration;
			}
			return currentPostion;
		} else if (player != null && player.isPlaying()) {
			int pos = player.getCurrentPosition();
			if (pos > 0) {
				currentPostion = pos;
			}
			if (ft != 0 && pos >= ft && vip && !UserInfoManager.isVip()) {// 非vip用户
				// 非vip,暂停播放
				pause();
				sendMessage2UI(FONE_PLAYER_MSG_SHOW_VIP_PAGE);
			}
		}
		L.v(TAG, "currentPostion == " + currentPostion);
		return currentPostion;
	}

	@Override
	public synchronized void play() {
		if (ft != 0 && currentPostion >= ft && vip && !UserInfoManager.isVip()) {// 非vip用户
			sendMessage2UI(FONE_PLAYER_MSG_SHOW_VIP_PAGE);
			return;
		}

		L.v(TAG, "play");
		if (isAirOneMode()) {
			airOneResume();
		} else if (player == null) {
			// 发送播放消息
			if (!TextUtils.isEmpty(xyzPlayUrl)) {
				VideoPlayerMessage msg = new VideoPlayerMessage();
				msg.what = VideoPlayerMessage.MESSGAE_CHANGE_VIDEO;
				msg.obj = new ChangeVideoEvent(xyzPlayUrl, true, true, false);
				EventBus.getDefault().post(msg);
			}
			// 要先进行判断是否已经关闭完成，关闭完成了再进行下一次播放
			if (isCloseSuccess) {
				L.v(TAG, "wwb_message  at once open 11");
				openSystemDecoder();
				open();
			} else {
				startTime = System.currentTimeMillis();
				mHandler.postDelayed(openPlayerRunnable, 1);
			}
		} else {
			player.play(); // 继续播放
			machine.play();
			sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PLAYING_PAUSE);
		}
	}

	private void openSystemDecoder() {
		if (mode == VideoMode.LOCAL && !isCacheVideo) {
			L.v(TAG, "open System_decoder");
			setSystem_decoder(1);// 本地视频支持硬解
			videoSurface.setVisibility(View.VISIBLE);
			AndroidPlayer.Uim_Set_Player_Surface(videoSurface);
		} else {
			L.v(TAG, "close System_decoder");
			setSystem_decoder(0);
		}
	}

	private long startTime;

	private Runnable openPlayerRunnable = new Runnable() {
		@Override
		public void run() {
			L.v(TAG, "wwb_message while" + this.getClass());
			if (!playerRelease) {
				if (isCloseSuccess || System.currentTimeMillis() - startTime > 3000) {
					L.v(TAG, "wwb_message  delay open" + this.getClass());
					openSystemDecoder();
					open();
				} else {
					mHandler.postDelayed(this, 1);
				}
			}
		}
	};

	/**
	 * 根据位置获取该位置属于第几片,从0开始
	 * 
	 * @param postion
	 * @return
	 * @return int 第几片 从0开始
	 * @throws
	 */
	private int getPlayIndexByPostion(int postion) {
		if (currentMedia != null) {
			if (currentMedia.fragDuration == null || currentMedia.fragDuration.length == 1 || postion == 0) {
				return 0;
			} else {
				int tempPostion = 0;
				for (int i = 0; i < currentMedia.fragDuration.length; i++) {
					if (postion > tempPostion && postion < (tempPostion + currentMedia.fragDuration[i])) {
						return i;
					}
					tempPostion += currentMedia.fragDuration[i];
				}
			}
		}
		return 0;
	}

	public void airOneOpen(final AirServerDevice device) {
		L.v(TAG, "airOneOpen");
		final String file;
		if (currentMedia != null && currentMedia.fragDuration != null && currentMedia.fragDuration.length > 0) {
			if (mode == VideoMode.LOCAL && currentMedia.fragUrl[0].startsWith("/")) {
				file = "http://" + AirOne.getLocalIpAndPort() + currentMedia.fragUrl[0];
			} else {
				airIndex = 0;
				if (currentMedia.fragUrl.length > 1) {
					// 多片视频
					long tempDuring = 0;
					for (int i = 0; i < currentMedia.fragDuration.length; i++) {
						tempDuring = tempDuring + currentMedia.fragDuration[i];
						if (currentPostion < tempDuring) {
							airIndex = i;
							currentPostion = (int) (currentMedia.fragDuration[i] - (tempDuring - currentPostion));
							break;
						}
					}
				}
				file = currentMedia.fragUrl[airIndex];
			}
			submitRunable(new Runnable() {
				@Override
				public void run() {
					airOneOpen(device, file, currentPostion);
				}
			});
			if (aironeThread == null) {
				aironeThread = new AirOneStateThread();
				aironeThread.setDaemon(true);
			}
			aironeThread.setRelease(false);
			if (!aironeThread.isAlive()) {
				aironeThread.start();
			}
			Toast.makeText(ApplicationManage.getAplicationManageInstance(), "尝试往[" + device.server_name + "]投放视频", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * airone打开投放设备
	 * 
	 * @param device
	 * @param url
	 * @param startPostion
	 *            单位毫秒
	 * @return
	 * @return boolean
	 * @throws
	 */
	private boolean airOneOpen(final AirServerDevice device, final String url, final int startPostion) {
		L.v(TAG, "airone open : " + device.server_name);
		int result = -1;
		if (device.proto == 0) {
			aironeTranslating = true;
			float seekPostion = 0;
			if (currentMedia.fragUrl.length > 1) {
				if (currentMedia.fragDuration.length > airIndex && currentMedia.fragDuration[airIndex] > 0) {
					seekPostion = (float) startPostion / (float) currentMedia.fragDuration[airIndex];
				}
			} else {
				seekPostion = (float) startPostion / (float) videoDuration;
			}
			L.v(TAG, "airone airplay open : " + device.server_name);
			result = FAirPlay.open(device.server_ip_addr, device.server_port, url, seekPostion);
		} else {
			result = FDLNAPlay.open(device.server_uid, url, "100tv", null, startPostion / 1000);
		}
		if (result == FDLNAPlay.RS_OK) {
			sendMessage2UI(FONE_PLAYER_MSG_AIRONE_TRANSLATION);
			// 进行验证是否投放成功
			aironeTranslating = true;
			boolean isOpenSuccess = false;
			int successTimes = 0;
			int faildTime = 0;
			int totalTimes = 0;
			while (aironeTranslating) {
				totalTimes++;
				int state = -1;
				try {
					if (device.proto == 0) {
						float scrubs[] = FAirPlay.getScrub(device.server_ip_addr, device.server_port);
						L.v(TAG, "airone airplay get scrub == " + scrubs[0] + " --- " + scrubs[1]);
						if (scrubs[0] <= 0 && scrubs[1] <= 0) {
							state = FAirPlay.PLAYSTATE_STOPPED;
						} else {
							state = FAirPlay.PLAYSTATE_PLAYING;
						}
					} else {
						state = FDLNAPlay.get_play_state(device.server_uid);
					}
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				L.v(TAG, "FDLNAPlay.get_play_state == " + state);
				if (state == CDLNAPlayer.PLAYSTATE_PLAYING || state == CDLNAPlayer.PLAYSTATE_TRANSITIONING) {// 正在播放
					successTimes++;
					if (successTimes >= 20) {
						aironeTranslating = false;
						isOpenSuccess = true;
						break;
					}
				} else if (state == CDLNAPlayer.PLAYSTATE_STOPPED) {// 打开失败
					faildTime++;
					if (faildTime >= 20) {
						device.checked = false;
						removeDevice(device.server_uid);
						airOneStopedHandle();
						aironeTranslating = false;
						isOpenSuccess = false;
						break;
					}
				}
				if (totalTimes > 40) {// 总次数40次以上为失败
					device.checked = false;
					removeDevice(device.server_uid);
					airOneStopedHandle();
					aironeTranslating = false;
					isOpenSuccess = false;
					break;
				}
			}
			if (!isOpenSuccess) {
				// 打开失败
				sendMessage2UI(FONE_PLAYER_MSG_AIRONE_OPEN_ERROR);
				return false;
			}
			if (deviceMap.get(device.server_uid) == null) {
				// 加入到投放map中
				if (deviceMapLock.tryLock()) {
					try {
						deviceMap.put(device.server_uid, device);
					} finally {
						deviceMapLock.unlock();
					}
				}
			}
			L.v(TAG, "airOneOpen FDLNAPlay.RS_OK ");
			// 直接投放
			machine.airone_play();
			device.player_state = FAirPlay.PLAYSTATE_PLAYING;
			Message msg = new Message();
			msg.what = FONE_PLAYER_MSG_AIRONE_START;
			msg.obj = device.server_name;
			sendMessage2UI(msg);
			if (player != null) {
				player.stop(true);
				player.release();
				player = null;
			}
			isPlaying = true;
			if (device.proto != 0) {
				if (startPostion > 10000) {
					aironeSeekToDevice(device, startPostion);
				}
			}
			return true;
		} else {
			L.v(TAG, "airOneOpen error");
			device.checked = false;
			removeDevice(device.server_uid);
			aironeTranslating = false;
			sendMessage2UI(FONE_PLAYER_MSG_AIRONE_OPEN_ERROR);
			airOneStopedHandle();
			return false;
		}
	}

	public void airOneResume() {
		submitRunable(new Runnable() {
			@Override
			public void run() {
				aironeTranslating = true;
				// 直接投放
				machine.airone_play();
				for (AirServerDevice d : AirOne.getInstance().getDevices()) {
					if (d.proto == 0) {
						FAirPlay.play(d.server_ip_addr, d.server_port);
					} else {
						FDLNAPlay.resume(d.server_uid);
					}
				}
				isPlaying = true;
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PLAYING_PAUSE);
				aironeTranslating = false;
			}
		});
	}

	public void airOneNext() {
		aironeTranslating = true;
		final String file;
		if (mode == VideoMode.LOCAL && currentMedia.fragUrl[0].startsWith("/")) {
			file = "http://" + AirOne.getLocalIpAndPort() + currentMedia.fragUrl[0];
		} else {
			file = currentMedia.fragUrl[airIndex];
		}
		// 直接投放
		videoDuration = 0;
		currentPostion = 0;
		if (deviceMap.size() > 0) {
			if (deviceMapLock.tryLock()) {
				try {
					Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
					while (it.hasNext()) {
						Entry<String, AirServerDevice> entry = it.next();
						final AirServerDevice device = entry.getValue();
						submitRunable(new Runnable() {
							@Override
							public void run() {
								if (airOneOpen(device, file, currentPostion)) {
									isPlaying = true;
									machine.airone_play();
								}
							}
						});
					}
				} finally {
					deviceMapLock.unlock();
				}
			}
		}
	}

	public void doAirOneStopDevice(final AirServerDevice airServerDevice) {
		if (deviceMapLock.tryLock()) {
			try {
				airServerDevice.checked = false;
				deviceMap.remove(airServerDevice.server_uid);
				airOneStop(airServerDevice);
			} finally {
				deviceMapLock.unlock();
			}
		}

	}

	private void airOneStop(final AirServerDevice airServerDevice) {
		submitRunable(new Runnable() {// dlna
			@Override
			public void run() {
				L.v(TAG, "airOneStop");
				// 停止投放
				if (airServerDevice.proto == 0) {
					// airplay
					FAirPlay.stop(airServerDevice.server_ip_addr, airServerDevice.server_port);
				} else {
					// dlna
					FDLNAPlay.stop(airServerDevice.server_uid);
				}
				airOneStopedHandle();
			}
		});
	}

	public void airOnePasue() {
		submitRunable(new Runnable() {
			@Override
			public void run() {
				aironeTranslating = true;
				// 暂停airone播放
				Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
				while (it.hasNext()) {
					AirServerDevice device = it.next().getValue();
					if (device.proto == 0) {
						FAirPlay.pause(device.server_ip_addr, device.server_port);
					} else {
						FDLNAPlay.pause(device.server_uid);
					}
				}
				isPlaying = false;
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_PLAYING_PAUSE);
				machine.airone_pause();
				aironeTranslating = false;
			}
		});
	}

	/**
	 * 投放视频调到pos毫秒处
	 * 
	 * @param pos
	 *            单位毫秒
	 * @return void
	 * @throws
	 */
	public void airOneSeek(final int pos) {
		submitRunable(new Runnable() {
			@Override
			public void run() {
				aironeTranslating = true;
				// airone seek to
				Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
				while (it.hasNext()) {
					int seekPos = pos;
					if (currentMedia.fragDuration.length > 1) {
						// 多片视频
						// 获取pos的位置在那一片
						int tempPos = 0;
						for (int i = 0; i < currentMedia.fragDuration.length; i++) {
							if (tempPos + currentMedia.fragDuration[i] > pos) {
								// 视频在这一片上
								// 是否播的就是这一片呢？
								if (airIndex == i) {
									// 播的也是这一片,转换seek位置
									seekPos = pos - tempPos;
									aironeSeekToDevice(it.next().getValue(), seekPos);
									break;
								} else {
									// 播的不是这一片,重新投放视频
									airIndex = i;
									airOneOpen(it.next().getValue(), currentMedia.fragUrl[i], seekPos);
									break;
								}
							}
							tempPos += currentMedia.fragDuration[i];
						}
					} else {
						aironeSeekToDevice(it.next().getValue(), seekPos);
					}
				}
				aironeTranslating = false;
			}
		});
	}

	/**
	 * seek设备device 到startPostion处
	 * 
	 * @param device
	 *            seek设备
	 * @param startPostion
	 *            seek位置 单位毫秒
	 * @return void
	 * @throws
	 */
	private synchronized void aironeSeekToDevice(final AirServerDevice device, int startPostion) {
		if (device.proto == 0) {
			// airplay
			FAirPlay.seek(device.server_ip_addr, device.server_port, startPostion / 1000);
		} else {
			// dlna
			FDLNAPlay.seek(device.server_uid, startPostion / 1000);
		}
	}

	public synchronized void airOneAddVolme(final int addVol) {
		submitRunable(new Runnable() {
			@Override
			public void run() {
				if (addVol != 0) {
					Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
					while (it.hasNext()) {
						AirServerDevice d = it.next().getValue();
						if (d.proto != 0) {
							int vol = FDLNAPlay.get_play_volume(d.server_uid);
							if (vol != FDLNAPlay.RS_ERROR) {
								vol = vol + addVol;
							}
							// 设置播放声音
							FDLNAPlay.set_volume(d.server_uid, vol);
						}
					}
				}
			}
		});
	}

	public void onChangedOrientation(int orientation) {
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			machine.changOrientationToLand();
			// 设置SurfaceView的大小
			setSurfaceScale(frameScale);
		} else {
			machine.changOrientationToPort();
			Message msg = new Message();
			msg.what = FONE_PLAYER_MSG_PLAYER_UPDATE_SURFACEVIEW;
			msg.arg1 = ScreenUtil.getScreenWidthPix(ApplicationManage.getAplicationManageInstance());
			msg.arg2 = ScreenUtil.dp2px(200);
			sendMessage2UI(msg);
		}
	}

	/**
	 * 是否是airone模式
	 * 
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean isAirOneMode() {
		if (machine.getCurrentState() == machine.getAironePlay() || machine.getCurrentState() == machine.getAironePause()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 进度条更新线程
	 * 
	 * @author kongxiaojun
	 * @since 2014-4-16
	 * 
	 */
	private class AirOneStateThread extends Thread {
		private boolean release;

		public void run() {
			while (!release) {
				if (isAirOneMode() && !aironeTranslating) {
					L.v(TAG, "airone thread running");
					if (deviceMap.size() > 0) {
						// 遍历选中设备
						if (deviceMapLock.tryLock()) {
							try {
								Iterator<Entry<String, AirServerDevice>> it = deviceMap.entrySet().iterator();
								while (it.hasNext()) {
									Entry<String, AirServerDevice> entity = it.next();
									AirServerDevice device = entity.getValue();
									if (device.checked) {
										if (device.proto != 0) {
											// dlna
											device.player_state = FDLNAPlay.get_play_state(device.server_uid);
										}
										L.v(TAG, "airone play state == " + device.player_state);
										if (device.player_state == CDLNAPlayer.PLAYSTATE_STOPPED) {// 播放完成
											device.checked = true;
											if (!doAirOneNext(device)) {
												it.remove();
											}
											break;
										} else if (device.player_state == CDLNAPlayer.PLAYSTATE_PLAYING || device.player_state == CDLNAPlayer.PLAYSTATE_PAUSED_PLAYBACK || device.player_state == CDLNAPlayer.PLAYSTATE_TRANSITIONING) {
											int tempPostion = 0;
											// 获取当前播放时间
											if (device.proto == 0) {
												// airplay
												float scrubs[] = FAirPlay.getScrub(device.server_ip_addr, device.server_port);
												float postion = scrubs[1];
												float duration = scrubs[0];
												if (postion > 0) {
													tempPostion = (int) (postion * 1000);
												}
												if (duration <= 0 && postion <= 0) {
													device.player_state = FAirPlay.PLAYSTATE_UNKNOWN;
												} else {
													device.error_times = 0;
													if (!isLiveVideo() && postion + 5 >= duration) {
														// 设备停止
														device.player_state = FAirPlay.PLAYSTATE_STOPPED;
													}
												}
											} else {
												device.error_times = 0;
												int res = FDLNAPlay.get_play_curtime(device.server_uid);
												L.v(TAG, "airone get_play_curtime == " + res);
												if (res > 0) {
													tempPostion = res * 1000;
												}
											}
											if (tempPostion > 0) {
												// 处理多片/单片视频问题
												if (currentMedia.fragDuration.length > 1 && airIndex != 0) {// 多片视频
													currentPostion = 0;
													for (int i = 0; i < airIndex; i++) {
														currentPostion += currentMedia.fragDuration[i];
													}
													currentPostion += tempPostion;
													if (tempPostion + 2000 >= currentMedia.fragDuration[airIndex]) {
														// 下一片
														if (!doAirOneNext(device)) {
															it.remove();
														}
													}
													if (videoDuration <= 0) {
														for (int i = 0; i < currentMedia.fragDuration.length; i++) {
															videoDuration += currentMedia.fragDuration[i];
														}
													}
												} else {
													currentPostion = tempPostion;
													// 单片
													if (videoDuration > 0 && tempPostion + 1000 >= videoDuration) {
														// 下一集
														if (!doAirOneNext(device)) {
															it.remove();
														}
													}
													if (videoDuration <= 0) {
														if (currentMedia.fragDuration != null && currentMedia.fragDuration.length > 1) {
															for (int dur : currentMedia.fragDuration) {
																videoDuration += dur;
															}
														} else {
															if (device.proto == 0) {
																// airplay
																float scrubs[] = FAirPlay.getScrub(device.server_ip_addr, device.server_port);
																videoDuration = (int) (scrubs[0] * 1000);
															} else {
																videoDuration = FDLNAPlay.get_duration(device.server_uid) * 1000;
															}
														}
														if (videoDuration > 0) {
															sendMessage2UI(FONE_PLAYER_MSG_AIRONE_NEXT_SUCCESS);
														}
													}
												}

											}
											// 跳出循环
											break;
										} else if (device.player_state == CDLNAPlayer.PLAYSTATE_UNKNOWN) {// 设备断开
											device.error_times++;
											if (device.error_times >= 20) {
												device.error_times = 0;
												device.checked = false;
												it.remove();
												airOneStopedHandle();
											}
											Thread.sleep(500);
										}
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								deviceMapLock.unlock();
							}
						}
					}
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		public void setRelease(boolean release) {
			this.release = release;
		}

		/**
		 * airone 下一片/下一集
		 * 
		 * @param device
		 * @return
		 * @return boolean 是否有下一集/下一片
		 * @throws
		 */
		private boolean doAirOneNext(AirServerDevice device) {
			// 投放下一集视频
			try {
				if (airIndex + 1 >= currentMedia.fragUrl.length) {
					// 投放下一集
					airIndex = 0;
					if (!hasNext()) {
						// airone 没有下一部了
						// 删除所有airone设备
						device.checked = false;
						sendMessage2UI(FONE_PLAYER_MSG_AIRONE_NO_NEXT);
						return false;
					} else {
						aironeTranslating = true;
						Thread.sleep(1000);
						next();
						return true;
					}
				} else {
					// 投放下一片
					airIndex++;
					Thread.sleep(1000);
					airOneNext();
					return true;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return false;
		}

	}

	/**
	 * 更新视频信息
	 * 
	 * @return void
	 * @throws
	 */
	protected void updateVideoInfo() {
		switch (videoDetail.type) {
		case 0:// 剧集模式
			mode = VideoMode.SERIES;
			break;
		case 1:// 直播
			mode = VideoMode.LIVE;
			break;
		case 2:// 单片
			mode = VideoMode.SINGLE;
			break;
		case 3:// 段视频
			mode = VideoMode.SHORT;
			break;
		default:
			break;
		}
	}

	public void playCacheVideo(ArrayList<CacheVideo> videos, int index) {
		L.v(TAG, "playCacheVideo");
		isCacheVideo = true;
		encryption = false;
		vip = false;
		ft = 0;
		mode = VideoMode.LOCAL;
		this.cacheVideos = videos;
		playIndex = index;
		this.xyzPlayUrl = cacheVideos.get(index).getXyzplay();
		this.cacheFinish = cacheVideos.get(index).isDownFinish();
		sendMessage2UI(FONE_PLAYER_MSG_UPDATE_UI_DATA);
		updateCurrentMedia(cacheVideos.get(index).getUrls(), cacheVideos.get(index).getDurations(), 0, 1);
		play();
	}

	public boolean isEncryption() {
		return encryption;
	}

	public void setEncryption(boolean encryption) {
		this.encryption = encryption;
		currentPostion = 0;
	}

	@Override
	public void playUrl(int index, String... urls) {
		this.urls = new String[urls.length];
		for (int i = 0; i < urls.length; i++) {
			L.v(TAG, "playUrl url = " + xyzPlayUrl);
			String url = urls[i];
			if (url.startsWith("content://")) {
				url = StorageModule.getInstance().getFilePathByMediaUri(url);
				if (url.startsWith("file://")) {
					url = url.substring(7);
				}
				mode = VideoMode.LOCAL;
			} else if (url.startsWith("file://")) {
				url = url.substring(7);
				mode = VideoMode.LOCAL;
			} else if (url.startsWith("/")) {
				mode = VideoMode.LOCAL;
			} else if (url.startsWith("[host]/player/xyzplay")) {
				isCacheVideo = true;
				mode = VideoMode.LOCAL;
				url = url.replace("[host]/player", Configure.getEndPoint());
			} else {
				mode = VideoMode.NETWORK;
			}
			this.urls[i] = url;
		}
		xyzPlayUrl = this.urls[index];
		this.playIndex = index;
		sendMessage2UI(FONE_PLAYER_MSG_UPDATE_UI_DATA);
		updateCurrentMedia(new String[] { xyzPlayUrl }, new int[] { 0 }, 0, 0);
		play();
	}

	private void updateCurrentMedia(String[] urls, int[] duiations, int isInstanceVideo, int isCachePlay) {
		currentMedia = new TagFoneMediaInfo();
		currentMedia.fragUrl = urls;
		currentMedia.fragDuration = duiations;
		currentMedia.isCachePlay = isCachePlay;
		currentMedia.isInstanceVideo = isInstanceVideo;
		updatePlayRecord2MediaInfo();
	}

	public void updatePlayRecord2MediaInfo() {
		if (currentMedia != null) {
			PlayRecord record = getPlayRecord();
			if (record != null && record.getPlayRecordTotalTime() > 0 && record.getPlayRecordAlreadyPlayTime() > 4000 && record.getPlayRecordAlreadyPlayTime() + 5000 < record.getPlayRecordTotalTime()) {
				if (isVip() && record.getPlayRecordAlreadyPlayTime() + 1000 > ft && !UserInfoManager.isVip()) {
					currentMedia.seekPos = 0;
					currentPostion = 0;
					lastPosition = 0;
					return;
				}
				currentMedia.seekPos = (int) record.getPlayRecordAlreadyPlayTime();
				// 恢复播放记录位置
				Message msg = new Message();
				msg.what = FONE_PLAYER_MSG_RESUME_PLAY_PROGRESS;
				currentPostion = (int) record.getPlayRecordAlreadyPlayTime();
				msg.arg1 = (int) record.getPlayRecordAlreadyPlayTime();
				msg.arg2 = (int) record.getPlayRecordTotalTime();
				sendMessage2UI(msg);
			} else {
				currentMedia.seekPos = 0;
			}
		}

	}

	/**
	 * 
	 * 
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean hasNext() {
		if (mode == VideoMode.LOCAL || mode == VideoMode.NETWORK) {

			if (isCacheVideo) {
				if (cacheVideos.size() == 1) {
					// 只有一个视频
					// 没有下一部
					return false;
				} else {
					if (cacheVideos.size() <= playIndex + 1) {
						return false;
					} else {
						return true;
					}
				}
			}

			// 本地或者网络视频
			if (urls.length == 1) {
				// 只有一个视频
				// 没有下一部
				return false;
			} else {
				if (urls.length <= playIndex + 1) {
					return false;
				} else {
					return true;
				}
			}
		} else {
			// 剧集下一部
			if (plaRst != null && !TextUtils.isEmpty(plaRst.nexturl)) {
				// 剧集切到下一集
				return true;
			} else {
				return false;
			}
		}
	}

	@Override
	public void next() {
		L.v(TAG, "next");
		hasResumedPlayRecord = false;
		currentPostion = 0;
		if (mode == VideoMode.LOCAL) {

			if (isCacheVideo) {
				if (cacheVideos.size() == 1) {
					// 只有一个视频
					// 没有下一部
					return;
				} else {
					if (cacheVideos.size() <= playIndex + 1) {
						return;
					} else {
						if (!isAirOneMode()) {
							stop();
							release();
						}
						currentPostion = 0;
						playIndex++;
						currentMedia = new TagFoneMediaInfo();
						currentMedia.fragUrl = cacheVideos.get(playIndex).getUrls();
						currentMedia.fragDuration = cacheVideos.get(playIndex).getDurations();
						currentMedia.isCachePlay = 1;
						this.xyzPlayUrl = cacheVideos.get(playIndex).getXyzplay();
						cacheFinish = cacheVideos.get(playIndex).isDownFinish();
						if (isAirOneMode()) {
							airOneNext();
						} else {
							play();
						}
					}
				}
			} else if (urls.length == 1) {// 本地或者网络视频
				// 只有一个视频
				// 没有下一部
				return;
			} else {
				if (urls.length <= playIndex + 1) {
					return;
				} else {
					playIndex++;
				}
				if (!isAirOneMode()) {
					stop();
					release();
				}
				currentPostion = 0;
				lastPosition = 0;
				xyzPlayUrl = urls[playIndex];
				updateCurrentMedia(new String[] { urls[playIndex] }, new int[] { 0 }, 0, 0);
				if (isAirOneMode()) {
					airOneNext();
				} else {
					play();
				}
			}
			sendMessage2UI(FONE_PLAYER_MSG_UPDATE_UI_DATA);
			return;
		} else {
			// 剧集下一部
			if (plaRst != null && !TextUtils.isEmpty(plaRst.nexturl)) {
				if (isPlaying && !isAirOneMode()) {
					stop();
					release();
					aironeTranslating = true;
				}
				currentPostion = 0;
				// 剧集切到下一集
				sendMessage2UI(FONE_PLAYER_MSG_PLAYER_SERIES_NEXT);
				return;
			} else {
				return;
			}
		}
	}

	/**
	 * 切换省电加速状态
	 * 
	 * @return void
	 * @throws
	 */
	public void doSwithHwPlus(int state) {
		L.v(TAG, "doSwithHwPlus state == " + state);
		hardware_plus = state;
		open();
	}

	/**
	 * 切换至软解播放
	 * 
	 * @return void
	 * @throws
	 */
	public void doSwitchSwDecoder() {
		L.v(TAG, "doSwitchSwDecoder");
		hardware_plus = 0;
		system_decoder = 0;
		open();
	}

	public String getVideoName() {
		if (videoDetail == null) {
			if (plaRst == null) {
				if (isCacheVideo) {
					L.v(TAG, "getVideoName == " + cacheVideos.get(playIndex).getName());
					return cacheVideos.get(playIndex).getName();
				}
				// 播放的是本地视频或者URL
				if (currentMedia.fragUrl[0].startsWith("/")) {
					// 本地
					return currentMedia.fragUrl[0].substring(currentMedia.fragUrl[0].lastIndexOf("/") + 1);
				} else {
					// url
					return videoName;
				}
			} else {
				return plaRst.cnt.name;
			}
		} else {
			// 获取videoname
			if (plaRst != null) {
				return plaRst.cnt.name;
			}
			return videoDetail.name;
		}
	}

	public void setVideoMode(VideoMode mode2) {
		this.mode = mode2;
	}

	public void setVideoDetail(VgdetailRst rst, int fromIndex) {
		this.videoDetail = rst;
		if (rst == null) {
			return;
		}
		updateVideoInfo();
		if (videoDetail != null && videoDetail.froms != null && videoDetail.froms.fromList != null && videoDetail.froms.fromList.size() > 0) {
			if (fromIndex >= 0) {
				setCurrentFrom(videoDetail.froms.fromList.get(fromIndex));
			}
		}
		updateCacheFrom();
		sendMessage2UI(FONE_PLAYER_MSG_UPDATE_UI_DATA);
	}

	/**
	 * 获取当前视频VgdetailRst
	 * 
	 * @return
	 * @return VgdetailRst
	 * @throws
	 */
	public VgdetailRst getVideoDetail() {
		return videoDetail;
	}

	/**
	 * 获取当前播放来源
	 * 
	 * @return
	 * @return From
	 * @throws
	 */
	public From getCurrentFrom() {
		return currentFrom;
	}

	/**
	 * 更新缓存来源
	 * 
	 * @return void
	 * @throws
	 */
	private void updateCacheFrom() {
		cacheFrom = null;
		if (videoDetail != null && videoDetail.froms != null && videoDetail.froms.fromList != null) {
			if (videoDetail.froms.fromList.size() > 1) {
				// 找出最大集数
				int maxUpdateNum = -1;
				for (int i = 0; i < videoDetail.froms.fromList.size(); i++) {
					From from = videoDetail.froms.fromList.get(i);
					if (from.btndown == 1) {// 是否可以下载
						if (maxUpdateNum >= 0) {
							if (from.updatenum > maxUpdateNum) {
								maxUpdateNum = from.updatenum;
							}
						} else {
							maxUpdateNum = from.updatenum;
						}
					}
				}
				// 找出多个相同的集数的源
				List<From> maxFroms = new ArrayList<VgdetailRst.From>();
				for (From from : videoDetail.froms.fromList) {
					if (from.btndown == 1) {// 是否可以下载
						if (from.updatenum == maxUpdateNum) {
							maxFroms.add(from);
						}
					}
				}
				if (maxFroms.size() > 1) {
					// 遍历找出清晰度最高的
					// 先找三个清晰度都有的
					for (From from : maxFroms) {
						if (!TextUtils.isEmpty(from.dfnt) && from.dfnt.length() == 5) {
							// 有三个清晰度
							cacheFrom = from;
							return;
						}
					}
					if (cacheFrom == null) {
						// 依次找包含超清，高清，表情的视频来源
						for (int i = 3; i > 0; i--) {
							findCacheFromByDfnt(maxFroms, i + "");
							if (cacheFrom != null) {
								return;
							}
						}
					}
				} else if (maxFroms.size() > 0) {
					cacheFrom = maxFroms.get(0);
				}
			} else {
				if (videoDetail.froms.fromList.get(0).btndown == 1) {
					cacheFrom = videoDetail.froms.fromList.get(0);
				}
			}
		}
	}

	private void findCacheFromByDfnt(List<From> froms, String dfnt) {
		for (From from : froms) {
			if (from.dfnt.contains(dfnt)) {
				// 有三个清晰度
				cacheFrom = from;
				break;
			}
		}
	}

	/**
	 * 获取当前缓存来源,如果是空就不能缓存
	 * 
	 * @return
	 * @return From
	 * @throws
	 */
	public From getCacheFrom() {
		return cacheFrom;
	}

	/**
	 * 设置当前播放视频来源
	 * 
	 * @param from
	 * @return void
	 * @throws
	 */
	public void setCurrentFrom(From from) {
		this.currentFrom = from;
		if (currentFrom == null) {
			return;
		}
		// 获取剧集播放最新的集数
		if (videoDetail.type == 0) {
			try {
				long videoid = Long.valueOf(FoneUtil.getVideoIdByUrl(currentFrom.defaulturl));
				long ccid = Long.valueOf(FoneUtil.getCCIdByUrl(currentFrom.defaulturl));
				long cid = Long.valueOf(FoneUtil.getCIdByUrl(currentFrom.defaulturl));
				//最近播放的集数
				PlayRecord recentlyRecord = StorageModule.getInstance().getRecentlyPlayRecordByID(videoid, ccid);
				if (recentlyRecord != null) {
					if (recentlyRecord.getPlayRecordCID() != cid) {
						this.xyzPlayUrl = recentlyRecord.getPlayRecordPlayUrl();
					} else {
						this.xyzPlayUrl = currentFrom.defaulturl;
					}
				} else {
					this.xyzPlayUrl = currentFrom.defaulturl;
				}
				// 发送播放消息
				if (currentFrom.toply != 0 && !TextUtils.isEmpty(xyzPlayUrl)) {
					VideoPlayerMessage msg = new VideoPlayerMessage();
					msg.what = VideoPlayerMessage.MESSGAE_CHANGE_VIDEO;
					msg.obj = new ChangeVideoEvent(xyzPlayUrl, true, false, false);
					EventBus.getDefault().post(msg);
				}
			} catch (Exception e) {
				L.v(TAG, "获取剧集播放最新的集数异常！");
				e.printStackTrace();
				this.xyzPlayUrl = currentFrom.defaulturl;
			}
		} else {
			this.xyzPlayUrl = currentFrom.defaulturl;
		}
		sendMessage2UI(FONE_PLAYER_MSG_VIDEO_FROM_CHANGED);
	}

	public void setPlayerRst(XyzplaRst t, PlayerAction action) {
		this.plaRst = t;
		if (t == null) {
			currentMedia = null;
			vip = false;
			ft = 0;
			isCacheVideo = false;
			encryption = false;
			return;
		}
		vip = plaRst.cnt.ftv == 0 ? false : true;
		if (vip) {// vip影片
			ft = plaRst.cnt.ft * 1000;
			if (ft > MAX_VIP_FREE_TIME) {
				ft = MAX_VIP_FREE_TIME;
			}
		} else {
			ft = 0;
		}
		int isInstanceVideo = 0;
		if (isLiveVideo()) {// 直播
			isInstanceVideo = 1;
		} else {
			isInstanceVideo = 0;
		}
		String[] fragUrl = new String[t.cnt.fraglist.fragList.size()];
		int[] fragDuration = new int[t.cnt.fraglist.fragList.size()];
		for (int i = 0; i < t.cnt.fraglist.fragList.size(); i++) {
			fragUrl[i] = t.cnt.fraglist.fragList.get(i).url;
			fragDuration[i] = t.cnt.fraglist.fragList.get(i).t;
		}
		updateCurrentMedia(fragUrl, fragDuration, isInstanceVideo, 0);
		if (isAirOneMode()) {
			airOneNext();
		} else if (action == PlayerAction.FULLPLAY) {
			play();
		} else if (currentFrom == null || currentFrom.defaultplay == 1) {// 自动播放
			play();
		}
		isCacheVideo = false;
		encryption = false;
	}

	/**
	 * 设置3d
	 * 
	 * @param state
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean set3DState(int state) {
		if (player != null) {
			return player._setPlay3D(state);
		}
		return false;
	}

	/**
	 * 设置倍速
	 * 
	 * @param state
	 * @return
	 * @return boolean
	 * @throws
	 */
	public void setPlayRate(int rate) {
		if (rate == 3) {// 底层3代表1.8倍速，而这里3就代表2.0倍速
			rate = 4;
		}
		if (player != null) {
			boolean play = false;
			if (player.isPlaying()) {
				play = true;
				player.pause();
			}
			if (player._setPlayRate(rate)) {
				currentRate = rate == 4 ? 3 : rate;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (play) {
				player.play();
			}
		}
	}

	/**
	 * 获取所有音轨
	 * 
	 * @return
	 * @return List<String>
	 * @throws
	 */
	public List<String> getAudioChannels() {
		if (player != null) {
			if (getAudioChannelCount() == 0) {
				return null;
			}
			List<String> channels = new ArrayList<String>();
			for (int i = 0; i < getAudioChannelCount(); i++) {
				channels.add(player._get_audio_channel_desc(i));
			}
			return channels;
		}
		return null;
	}

	/**
	 * 获取音轨数量
	 * 
	 * @return
	 * @return List<String>
	 * @throws
	 */
	public int getAudioChannelCount() {
		int count = 0;
		if (player != null) {
			return player._get_audio_channel_count();
		}
		return count;
	}

	/**
	 * 获取所有字幕
	 * 
	 * @return
	 * @return List<String>
	 * @throws
	 */
	public List<String> getSubChannels() {
		if (player != null) {
			List<String> channels = new ArrayList<String>();
			for (int i = 0; i < player._get_sub_channel_count(); i++) {
				channels.add(player._get_sub_channel_desc(i));
			}
			return channels;
		}
		return null;
	}

	/**
	 * 获取字幕数量
	 * 
	 * @return
	 * @return List<String>
	 * @throws
	 */
	public int getSubCount() {
		int count = 0;
		if (player != null) {
			return player._get_sub_channel_count();
		}
		return count;
	}

	/**
	 * 获取当前字幕
	 * 
	 * @return
	 * @return int
	 * @throws
	 */
	public int getCurrentSubChannel() {
		if (player != null) {
			return player._get_cur_sub_channel();
		}
		return 0;
	}

	/**
	 * 设置当前字幕index
	 * 
	 * @param sub
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean setCurrentSubChannel(int sub) {
		if (player != null) {
			player._set_cur_sub_channel(sub);
			return true;
		}
		return false;
	}

	/**
	 * 获取当前音轨
	 * 
	 * @return
	 * @return int
	 * @throws
	 */
	public int getCurrentAudioChannel() {
		if (player != null) {
			return player._get_cur_audio_channel();
		}
		return 0;
	}

	/**
	 * 设置当前音轨
	 * 
	 * @param channel
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean setCurrentAudioChannel(int channel) {
		if (player != null) {
			player._set_cur_audio_channel(channel);
			return true;
		}
		return false;
	}

	/**
	 * 获取解码模式
	 * 
	 * @return int 0.省电加速;1.硬解码;2.软解;-1.不能获取解码模式
	 * @throws
	 */
	public int getPlayerDecoderRole() {
		if (player != null) {
			return player._get_player_decoder_role();
		}
		return -1;
	}

	/**
	 * 屏幕比例 0.等比例全屏;1.全屏拉伸;2.原始比例
	 * 
	 */
	private int frameScale = 0;

	public int getFrameScale() {
		return frameScale;
	}

	/**
	 * 切换屏幕比例
	 * 
	 * @return void
	 * @throws
	 */
	public void doChangeFrameScale() {
		if (player != null) {
			frameScale++;
			if (frameScale > 2) {
				frameScale = 0;
			}
			setSurfaceScale(frameScale);
		}
	}

	public static int getHwPlusSupport() {
		return hardware_plus;
	}

	public static void setHwPlusSupport(int state) {
		hardware_plus = state;
	}

	public static int getSystem_decoder() {
		return system_decoder;
	}

	public static void setSystem_decoder(int system_decoder) {
		FonePlayerAdapter.system_decoder = system_decoder;
	}

	/**
	 * 设置屏幕显示比例，全屏模式时可用
	 * 
	 * @param mode
	 * @return void
	 * @throws
	 */
	public void setSurfaceScale(int mode) {
		int nScreenWidth = ScreenUtil.getScreenWidthPix(ApplicationManage.getAplicationManageInstance());
		int nScreenHeight = ScreenUtil.getScreenHeightPix(ApplicationManage.getAplicationManageInstance());
		if (nScreenWidth < nScreenHeight) {
			nScreenWidth = nScreenHeight;
			nScreenHeight = ScreenUtil.getScreenWidthPix(ApplicationManage.getAplicationManageInstance());
		}

		int width = 0;
		int height = 0;

		if (nScreenWidth < nScreenHeight) {
			int temp = nScreenWidth;
			nScreenWidth = nScreenHeight;
			nScreenHeight = temp;
		}
		switch (mode) {
		case 2:// 切换至原始比例
			if (nScreenWidth < mediaWidth || nScreenHeight < mediaHeight) {
				float previewScale = (float) nScreenWidth / nScreenHeight;
				float mediaScale = (float) mediaWidth / mediaHeight;
				if (previewScale > mediaScale) {
					width = (int) (nScreenHeight * mediaScale);
					height = nScreenHeight;
				} else {
					width = nScreenWidth;
					height = (int) (nScreenWidth / mediaScale);
				}
			} else {
				width = mediaWidth;
				height = mediaHeight;
			}
			break;

		case 0: // 等比例全屏
			float previewScale = (float) nScreenWidth / nScreenHeight;
			float mediaScale = (float) mediaWidth / mediaHeight;
			if (previewScale > mediaScale) {
				width = (int) (nScreenHeight * mediaScale);
				height = nScreenHeight;
			} else {
				width = nScreenWidth;
				height = (int) (nScreenWidth / mediaScale);
			}
			break;

		case 1:// 全屏拉伸
			width = nScreenWidth;
			height = nScreenHeight;
			break;
		}
		Message msg = new Message();
		msg.what = FONE_PLAYER_MSG_PLAYER_UPDATE_SURFACEVIEW;
		msg.arg1 = width;
		msg.arg2 = height;
		sendMessage2UI(msg);
	}

	public String getXyzPlayUrl() {
		return xyzPlayUrl;
	}

	public void setXyzPlayUrl(String xyzPlayUrl) {
		this.xyzPlayUrl = xyzPlayUrl;
	}

	public XyzplaRst getPlaRst() {
		return plaRst;
	}

	/**
	 * 保存当前播放进度
	 * 
	 * @return void
	 * @throws
	 */
	public void savePlayRecord() {
		L.v(TAG, "savePlayRecord url = " + xyzPlayUrl);
		if (encryption || currentPostion == 0 || isLiveVideo()) {
			return;
		}
		PlayRecord record = new PlayRecord();
		if (isCacheVideo) {
			if (!cacheFinish) {
				return;
			}
			record.setPlayRecordType(PlayRecord.RECORD_PLAYER_CACHE);
			record.setPlayRecordPlayUrl(cacheVideos.get(playIndex).getXyzplay());
			record.setPlayRecordImageUrl(cacheVideos.get(playIndex).getPic());
			record.setPlayRecordCID(FoneUtil.String2Long(FoneUtil.getCIdByUrl(cacheVideos.get(playIndex).getXyzplay())));
			record.setPlayRecordCCID(FoneUtil.String2Long(FoneUtil.getCCIdByUrl(cacheVideos.get(playIndex).getXyzplay())));
			record.setPlayRecordCLID(FoneUtil.String2Long(FoneUtil.getCLIdByUrl(cacheVideos.get(playIndex).getXyzplay())));
			record.setPlayRecordVideoID(FoneUtil.String2Long(FoneUtil.getVideoIdByUrl(cacheVideos.get(playIndex).getXyzplay())));
		} else if (mode == VideoMode.LOCAL) {
			record.setPlayRecordType(PlayRecord.RECORD_PLAYER_LOCAL);
			record.setPlayRecordPlayUrl(urls[playIndex]);
			record.setPlayRecordImageUrl(urls[playIndex]);
		} else if (mode == VideoMode.NETWORK) {
			record.setPlayRecordType(PlayRecord.RECORD_WEB_NETWORK);
			record.setPlayRecordPlayUrl(urls[playIndex]);
			record.setPlayRecordName(videoName);
		} else {
			record.setPlayRecordPlayUrl(xyzPlayUrl);
			if (fromWebView) {
				record.setPlayRecordType(PlayRecord.RECORD_WEB_SOURCE);
				record.setPlayRecordExternalUrl(plaRst.cnt.ourl);
				record.setPlayRecordIsShowPlayButton(true);
			} else {
				record.setPlayRecordType(PlayRecord.RECORD_PLAYER_NETWORK);
			}
			String durl = record.getPlayRecordPlayUrl().replace("xyzplay", "vgdetail");
			record.setPlayRecordDetailUrl(durl);
			if (getVideoDetail() != null) {
				if (!TextUtils.isEmpty(getVideoDetail().pic)) {
					record.setPlayRecordImageUrl(getVideoDetail().pic.replace("[shost]", getVideoDetail().shost));
				}
				record.setPlayRecordContentType(getCurrentFrom().favtyp);
				record.setPlayRecordDescription(getVideoDetail().desc);
			}
			if (plaRst != null) {
				record.setPlayRecordFavouriteUrl(plaRst.furl);
				record.setPlayRecordContentType(FoneUtil.String2Integer(plaRst.cnt.favtyp));
				record.setPlayRecordShareUrl(plaRst.weibourl);
				if (!TextUtils.isEmpty(plaRst.cnt.pic)) {
					record.setPlayRecordImageUrl(plaRst.cnt.pic.replace("[shost]", plaRst.shost));
				}
				record.setPlayRecordIsVIP(plaRst.cnt.ftv == 0 ? false : true);
			}
			// record.setPlayRecordRemoveUrl();
			// record.setPlayRecordEpisodeUpdateInfo(PlayRecordEpisodeUpdateInfo);
			record.setPlayRecordCID(FoneUtil.String2Long(FoneUtil.getCIdByUrl(xyzPlayUrl)));
			record.setPlayRecordCCID(FoneUtil.String2Long(FoneUtil.getCCIdByUrl(xyzPlayUrl)));
			record.setPlayRecordCLID(FoneUtil.String2Long(FoneUtil.getCLIdByUrl(xyzPlayUrl)));
			record.setPlayRecordVideoID(FoneUtil.String2Long(FoneUtil.getVideoIdByUrl(xyzPlayUrl)));
		}
		record.setPlayRecordName(getVideoName());
		record.setPlayRecordAlreadyPlayTime(currentPostion);
		record.setPlayRecordTotalTime(videoDuration);
		record.setPlayRecordCreateTime(System.currentTimeMillis());
		// StorageModule.getInstance().addPlayRecord(record);
		L.v(TAG, "savePlayRecord : " + record.toString());
		PlayRecordFragment.addRecord(record);
	}

	/**
	 * 获取播放记录
	 * 
	 * @return 如果是null就没有播放记录，否则就是有播放记录
	 */
	private PlayRecord getPlayRecord() {
		L.v(TAG, "getPlayRecord");
		if (isCacheVideo && !cacheFinish && TextUtils.isEmpty(xyzPlayUrl)) {
			return null;
		}
		PlayRecord record = null;
		if (vip) {// vip视频通过videoId取
			String videoId = FoneUtil.getVideoIdByUrl(xyzPlayUrl);
			if (!TextUtils.isEmpty(videoId)) {
				record = StorageModule.getInstance().getPlayRecordByVideoID(Long.valueOf(videoId));
			}
		} else {
			if (mode == VideoMode.LOCAL || mode == VideoMode.NETWORK) {
				record = StorageModule.getInstance().getPlayRecordByPlayUrl(xyzPlayUrl);
			} else {
				String cid = FoneUtil.getCIdByUrl(xyzPlayUrl);
				if (!TextUtils.isEmpty(cid)) {
					record = StorageModule.getInstance().getPlayRecordByCID(Long.valueOf(cid));
				}
			}
		}
		if (record != null) {
			L.v(TAG, "getPlayRecord : " + record.toString());
		}
		return record;
	}

	// /**
	// * 恢复播放记录位置
	// *
	// * @return void
	// * @throws
	// */
	// public void resumePlayRecord() {
	// L.v(TAG, "resumePlayRecord");
	// if (encryption || (isCacheVideo && !cacheFinish)) {
	// return;
	// }
	// if (!hasResumedPlayRecord) {
	// L.v(TAG, "resumePlayRecord hasResumedPlayRecord == " +
	// hasResumedPlayRecord);
	// hasResumedPlayRecord = true;
	// // 恢复播放记录位置
	// Message msg = new Message();
	// msg.what = FONE_PLAYER_MSG_RESUME_PLAY_PROGRESS;
	// currentPostion = (int) record.getPlayRecordAlreadyPlayTime();
	// msg.arg1 = (int) record.getPlayRecordAlreadyPlayTime();
	// msg.arg2 = (int) record.getPlayRecordTotalTime();
	// sendMessage2UI(msg);
	// if (currentMedia.fragUrl.length > 1) {
	// L.v(TAG, "wwb_message  resume  set opendone");
	// openDone = false;
	// }
	// player.seekTo((int) record.getPlayRecordAlreadyPlayTime());
	// }
	// }

	/**
	 * 获取缓存的位置
	 * 
	 * @return
	 * @return int
	 * @throws
	 */
	public int getCachePosition() {
		if (player != null) {
			return player.getCachePosition();
		}
		return 0;
	}

	public String getShost() {
		return shost;
	}

	public void setShost(String shost) {

		this.shost = shost;
	}

	public void setCurrentPostion(int currentProgress) {
		this.currentPostion = currentProgress;
	}

	/**
	 * 获取当前倍速索引 0-->0.8倍速,1-->正常速度,2-->1.5倍速,3-->1.8倍速,4-->2倍速
	 * 
	 * @return
	 * @return int
	 * @throws
	 */
	public int getCurrentRate() {
		return currentRate;
	}

	public void setVideoName(String videoName) {
		this.videoName = videoName;
	}

	/**
	 * 是否vip影片
	 * 
	 * @return
	 * @return boolean
	 * @throws
	 */
	public boolean isVip() {
		return vip;
	}

	public void setVip(boolean vip) {
		this.vip = vip;
	}

	public boolean isCacheVideo() {
		return isCacheVideo;
	}

	public void setCacheVideo(boolean isCacheVideo) {
		this.isCacheVideo = isCacheVideo;
	}

	public boolean isFromWebView() {
		return fromWebView;
	}

	public void setFromWebView(boolean fromWebView) {
		this.fromWebView = fromWebView;
	}

	/**
	 * 是否是直播视频
	 * 
	 * @return
	 * @return boolean true 是直播,false非直播
	 * @throws
	 */
	public boolean isLiveVideo() {
		if (plaRst != null) {
			if (!TextUtils.isEmpty(plaRst.ds) && !plaRst.ds.equals("0")) {
				return true;
			}
		}
		if (videoDetail != null && videoDetail.type == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 提交线程到线程池
	 * 
	 * @param runnable
	 */
	public void submitRunable(Runnable runnable) {
		if (threadPool == null) {
			threadPool = Executors.newFixedThreadPool(poolSize);
		}
		threadPool.submit(runnable);
	}

	/**
	 * 删除指定设备
	 * 
	 * @param uid
	 */
	private void removeDevice(String uid) {
		if (deviceMap.get(uid) != null) {
			// 从map中删除中
			if (deviceMapLock.tryLock()) {
				try {
					AirServerDevice device = deviceMap.remove(uid);
					device.checked = false;
				} finally {
					deviceMapLock.unlock();
				}
			}
		}
	}

	/**
	 * 投放停止处理
	 */
	private void airOneStopedHandle() {
		if (deviceMap.size() <= 0) {
			savePlayRecord();
			machine.airone_stop();
			L.v(TAG, "FONE_PLAYER_MSG_AIRONE_STOPED");
			sendMessage2UI(FONE_PLAYER_MSG_AIRONE_STOPED);
			hasResumedPlayRecord = false;
		}
	}

	/**
	 * 设置SurfaceView
	 * 
	 * @param surfaceView
	 * @return void
	 * @throws
	 */
	public void setSurfaceView(SurfaceHolder holder) {
		if (player != null) {
			player._setSurface(holder.getSurface());
		}
	}

	public void setPlayerRelease(boolean playerRelease) {
		this.playerRelease = playerRelease;
	}

	public boolean isOpenSuccess() {
		return openDone;
	}

	public boolean isSeeking() {
		return isSeeking;
	}

	public boolean isSystemPlayerOpenFailed() {
		return systemPlayerOpenFailed;
	}

	public void setSystemPlayerOpenFailed(boolean systemPlayerOpenFailed) {
		this.systemPlayerOpenFailed = systemPlayerOpenFailed;
	}
	
	public void setComeFrom(int from) {
		comeFrom = from;
	}

}
